package com.summer.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.summer.entity.OrderBorrow;
import com.summer.mapper.OrderBorrowMapper;
import com.summer.service.IOrderBorrowService;
import com.summer.util.BuildXLSX;
import com.summer.util.CallBackResult;
import com.summer.util.XlsxParam;
import com.summer.variable.Constant;
import com.summer.vo.BorrowUserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Desc:
 * Created by tl on 2018/12/20
 */
@Controller
@RequestMapping("/v1.0/api/borrowOrder")
public class OrderBorrowController {
    private static Logger log = LoggerFactory.getLogger(OrderBorrowController.class);
    @Resource
    private IOrderBorrowService orderBorrowService;
    @Resource
    private OrderBorrowMapper orderBorrowMapper;

    /**
     * 审核订单列表
     *
     * @param jsonData
     * @return
     */
    @ResponseBody
    @PostMapping("/queryWithUser")
    public String queryWithUser(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderBorrowController queryWithUser params=" + params.toString());
        Object statusObj = params.get("status");
        if (null == statusObj) {
            //筛选复审
            params.put("review", "true");
        }
        PageHelper.startPage(params);
        PageInfo<BorrowUserVO> pageInfo = orderBorrowService.queryWithUser(params);
        return CallBackResult.returnJson(pageInfo);
    }

    /**
     * 放款记录列表
     *
     * @param jsonData
     * @return
     */
    @ResponseBody
    @PostMapping("/queryWithUserPass")
    public String queryWithUserPass(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderBorrowController queryWithUserPass params=" + params.toString());
        Object statusObj = params.get("status");
        if (null == statusObj) {
            //筛选放款
            params.put("pass", "true");
        }
        PageHelper.startPage(params);
        //TODO CHECK BANK ACCOUNT
        PageInfo<BorrowUserVO> pageInfo = orderBorrowService.queryWithUser(params);
        return CallBackResult.returnJson(pageInfo);
    }

    /**
     * 机审未通过列表
     *
     * @param jsonData
     * @return
     */
    @ResponseBody
    @PostMapping("/queryDenied")
    public String queryDenied(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderBorrowController queryDenied params=" + params.toString());
        Object statusObj = params.get("status");
        if (null == statusObj) {
            //机审未通过
            params.put("denied", "true");
        }
        PageHelper.startPage(params);
        PageInfo<BorrowUserVO> pageInfo = orderBorrowService.queryWithUser(params);
        return CallBackResult.returnJson(pageInfo);
    }

    /**
     * 重新审核
     *
     * @param jsonData
     * @return
     */
    @PostMapping("/toReview")
    @ResponseBody
    public String toReview(@RequestBody String jsonData) throws Exception {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderBorrowController toReview params=" + params.toString());
        OrderBorrow orderBorrow = checkId(params);
        if (null == orderBorrow)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "参数非法");
        OrderBorrow newOrder = new OrderBorrow();
        newOrder.setId(orderBorrow.getId());
        newOrder.setStatus(Constant.BORROW_STATUS_REVIEW_PERSON);
        orderBorrowService.updateSelective(newOrder);
        return CallBackResult.returnJson("操作成功");
    }

    /**
     * 重新放款
     *
     * @param jsonData
     * @return
     */
    @PostMapping("/reloan")
    @ResponseBody
    public String reloan(@RequestBody String jsonData) throws Exception {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderBorrowController reloan params=" + params.toString());
        OrderBorrow orderBorrow = checkId(params);
        if (null == orderBorrow)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "参数非法");
        OrderBorrow newOrder = new OrderBorrow();
        newOrder.setId(orderBorrow.getId());
        newOrder.setStatus(Constant.BORROW_STATUS_REVIEW_PASS);
        orderBorrowService.updateSelective(newOrder);
        return CallBackResult.returnJson("操作成功");
    }
    /**
     * 转派
     *
     * @param jsonData
     * @return
     */
    @PostMapping("/redistribute")
    @ResponseBody
    public String redistribute(@RequestBody String jsonData) throws Exception {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderBorrowController reDistribute params=" + params.toString());
        OrderBorrow orderBorrow = checkId(params);
        if (null == orderBorrow)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "参数非法");
        //TODO CHECK BACKUSER
        Object platformUserId = params.get("platformUserId");
        if (null == platformUserId)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "参数非法");
        OrderBorrow newOrder = new OrderBorrow();
        newOrder.setId(orderBorrow.getId());

        newOrder.setReviewUserId(Integer.parseInt(platformUserId.toString()));
        orderBorrowService.updateSelective(newOrder);
        return CallBackResult.returnJson("操作成功");
    }
    /**
     * 人工复审
     *
     * @param jsonData
     * @return
     */
    @PostMapping("/review")
    @ResponseBody
    public String review(@RequestBody String jsonData) throws Exception {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderBorrowController review params=" + params.toString());
        OrderBorrow orderBorrow = checkId(params);
        if (null == orderBorrow)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "参数非法");
        Object status = params.get("status");
        if (null == status)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "参数非法");
        OrderBorrow newOrder = new OrderBorrow();
        newOrder.setId(orderBorrow.getId());
        Object remark = params.get("remark");
        if (null != remark) {
            newOrder.setReviewRemark(remark.toString());
        }
        byte statusByte = Byte.parseByte(status.toString());
        if (Constant.BORROW_STATUS_REVIEW_PASS == statusByte) {
            newOrder.setStatus(Constant.BORROW_STATUS_REVIEW_PASS);
        } else if (Constant.BORROW_STATUS_REVIEW_REJECT == statusByte) {
            newOrder.setStatus(Constant.BORROW_STATUS_REVIEW_REJECT);
        }
        newOrder.setReviewTime(new Date());
        orderBorrowService.updateSelective(newOrder);
        return CallBackResult.returnJson("操作成功");
    }

    /**
     * 导出审核订单列表
     *
     * @param request
     * @param response
     * @param params
     * @throws Exception
     */
    @RequestMapping("downloadOrderReview")
    public void downloadOrderReview(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam Map<String, Object> params) throws Exception {
        log.info("OrderBorrowController downloadOrderReview params=" + params.toString());
        Object statusObj = params.get("status");
        if (null == statusObj) {
            //筛选复审
            params.put("review", "true");
        }
        List<BorrowUserVO> orderBorrows = orderBorrowMapper.findParams(params);
        log.info("OrderBorrowController downloadOrderReview size=" + orderBorrows.size());
        String title = "审核订单列表";
        BuildXLSX.setFileDownloadHeader(request, response, title);
        LinkedHashMap<String, String> titleMap = new LinkedHashMap<>();
        titleMap.put("createTimeChg", "申请时间");
        titleMap.put("realName", "客户姓名");
        titleMap.put("phone", "手机号码");
        titleMap.put("channelName", "渠道来源");
        titleMap.put("amountAvailable", "可借金额");
        titleMap.put("applyAmount", "申请金额");

        titleMap.put("loanTerm", "借款期限");
        titleMap.put("status", "审批状态");
        titleMap.put("reviewRemark", "不通过原因");
        titleMap.put("renewalCount", "续期次数");
        titleMap.put("reviewer", "审核人");
        titleMap.put("outTradeNo", "订单号");
        XlsxParam xlsxParam = new XlsxParam(orderBorrows, title, titleMap);
        OutputStream os = response.getOutputStream();
        BuildXLSX.buildExcel(xlsxParam, os);
    }

    /**
     * 导出放款订单列表
     *
     * @param request
     * @param response
     * @param params
     * @throws Exception
     */
    @RequestMapping("downloadOrderPass")
    public void downloadOrderPass(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam Map<String, Object> params) throws Exception {
        log.info("OrderBorrowController downloadOrderPass params=" + params.toString());
        Object statusObj = params.get("status");
        if (null == statusObj) {
            //筛选放款
            params.put("pass", "true");
        }
        List<BorrowUserVO> orderBorrows = orderBorrowMapper.findParams(params);
        log.info("OrderBorrowController downloadOrderPass size=" + orderBorrows.size());
        for (BorrowUserVO orderBorrow : orderBorrows) {
            orderBorrow.setLoanAmount(orderBorrow.getIntoMoney() + orderBorrow.getLoanFee());
        }
        String title = "放款订单列表";
        BuildXLSX.setFileDownloadHeader(request, response, title);
        LinkedHashMap<String, String> titleMap = new LinkedHashMap<>();
        titleMap.put("loanTimeChg", "放款时间");
        titleMap.put("realName", "客户姓名");
        titleMap.put("phone", "手机号码");
        titleMap.put("applyAmount", "申请金额");
        titleMap.put("createTimeChg", "申请时间");
        titleMap.put("loanTerm", "借款期限");

        titleMap.put("loanAmount", "批复金额");
        titleMap.put("intoMoney", "实际到账金额");

        titleMap.put("status", "放款状态");
        titleMap.put("payRemark", "失败原因");
        titleMap.put("bankCardId", "放款账户");
        titleMap.put("outTradeNo", "交易号");
        titleMap.put("reviewer", "审核人");
        XlsxParam xlsxParam = new XlsxParam(orderBorrows, title, titleMap);
        OutputStream os = response.getOutputStream();
        BuildXLSX.buildExcel(xlsxParam, os);
    }

    private OrderBorrow checkId(Map<String, Object> params) {
        Object idObj = params.get("id");
        if (null == idObj) {
            return null;
        }
        return orderBorrowMapper.selectByPrimaryKey(Integer.parseInt(idObj.toString()));
    }

}